package com.hs.monitor.communication;

import com.hs.monitor.entity.Para;
import com.hs.monitor.message.Receiver;
import com.hs.monitor.utils.ByteUtil;
import com.hs.monitor.utils.LogUtil;
import lombok.Data;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

@Data
public class Mqtt {

    private static MqttClient mqttClient;

    public static void createClient(Para para) {
//        String broker = "tcp://localhost:1883"; // MQTT代理地址
//        String clientId = "JavaSample"; // 客户端ID，唯一标识
//        String topic = "device/data"; // 主题

        String broker = "tcp://" + para.getHost() + ":" + para.getPort();

        MemoryPersistence persistence = new MemoryPersistence();
        try {
            mqttClient = new MqttClient(broker, para.getSn(), persistence);

        } catch (MqttException e) {
            System.out.println("创建客户端异常");
        }

        // 设置回调函数
        MqttClient finalMqttClient = mqttClient;
        MqttCallback callback = new MqttCallback() {

            @Override
            public void connectionLost(Throwable throwable) {
//                System.out.println("连接丢失，尝试重新连接...throwable="+throwable);
//                LogUtil.log("连接丢失，尝试重新连接...throwable="+throwable);
//                try {
//                    finalMqttClient.connect();
//                    System.out.println("重新连接成功！");
//                } catch (MqttException e) {
//                    e.printStackTrace();
//                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) {
//                System.out.println("接收到消息主题：" + topic);
                LogUtil.log("接收到消息主题：" + topic);
                byte[] payload = mqttMessage.getPayload();
//                System.out.println("接收到消息内容：" + ByteUtil.bytesToHex(payload));
                LogUtil.log("平台>>>设备：" + ByteUtil.bytesToHex(payload));
                Receiver.receive(payload);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//                System.out.println("消息发送成功！");
                LogUtil.log("消息发送成功");
            }
        };

        mqttClient.setCallback(callback);

        // 连接MQTT代理
        try {
            // 设置MQTT连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName("root");
            connOpts.setPassword("root".toCharArray());
            connOpts.setKeepAliveInterval(60); // 设置连接的心跳间隔，单位为秒
            mqttClient.connect(connOpts);
        } catch (MqttException e) {
            System.out.println("连接异常");
            throw new RuntimeException(e);
        }
//        System.out.println("已连接到MQTT代理：" + broker);
        LogUtil.log("已连接到MQTT代理");


        try {
            // 订阅主题
            mqttClient.subscribe(para.getTopicSubscribe());
//            System.out.println("订阅主题：" + para.getTopicSubscribe());
            LogUtil.log("订阅主题：" + para.getTopicSubscribe());
        } catch (Exception e) {
            System.out.println("订阅异常");
            e.printStackTrace();
        }

    }

    public static void publish(String topic, MqttMessage message) {
        try {
            mqttClient.publish(topic, message);
        } catch (MqttException e) {
            System.out.println("发布失败");
        }
    }

    public static void disconnect() {
        try {
            mqttClient.disconnect();
        } catch (MqttException e) {
            System.out.println("断开连接异常");
        }
    }


    public static void main(String[] args) {

    }
}
